package com.work.mp.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.work.sys.domain.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;


/**
 * @author lee
 * @date 2021/04/18
 */
@Service
public class MpTokenService {

    private static final Logger logger = LoggerFactory.getLogger(MpTokenService.class);


    public String getToken(SysUser userInfo) {
        return JWT.create().withAudience(String.valueOf(userInfo.getUserId()))// 将 member id 保存到 token 里面
                .sign(Algorithm.HMAC256(userInfo.getOpenId()));// 以 openid 作为 token 的密钥;
    }


    public Long getUserId(String token) {
        try {
            return Long.parseLong(JWT.decode(token).getAudience().get(0));
        } catch (JWTDecodeException j) {
            logger.error("从token获取会员id异常，token为：{}", token);
        }
        return 0L;
    }
}
